package com.hgk.wanwan.main;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.common.android.volley.VolleyError;
import com.common.android.volley.toolbox.RequestListener;
import com.common.android.volley.toolbox.VolleyManager;
import com.common.dongqiuhui.apps.comm.constants.KeysConstans;
import com.common.dongqiuhui.apps.comm.tools.BallUtil;
import com.common.dongqiuhui.apps.comm.util.SharedPreferencesUtil;
import com.hgk.common.common.constants.DataConstants;
import com.hgk.common.common.constants.StatisticConstants;
import com.hgk.common.common.ui.activity.BaseFragmentActivity;
import com.hgk.common.common.util.StatisticsUtil;
import com.hgk.wanwan.main.fragment.JumpLoginFragment;
import com.hgk.wanwan.main.fragment.persentfragment.PercentFragment;
import com.hgk.wanwan.main.fragment.pushfragment.PushFragment;
import com.hgk.wanwan.main.fragment.showfragment.ShowNowFragment;
import com.hgk.wanwan.main.fragment.whatfragment.WhatNowFragment;
import com.hgk.wanwan.main.fragment.wherefragment.WhereNowFragment;
import com.hgk.wanwan.main.msgmodel.UnreadMsgBean;
import com.hgk.wanwan.main.msgmodel.UpdataInfoBean;
import com.hgk.wanwan.main.service.UpdataService;

import java.util.HashMap;
import java.util.Map;

import width.hgk.wanwan.R;

public class MainActivity extends BaseFragmentActivity {

//    private final String UPDATE_APP_VERSON_URL = UrlConstans.ZWCOMMOMURL + "/admin/update.json";
//    private final String UNREAD_MSG_URL = UrlConstans.ZWCOMMOMURL + "/user/msg_num.json";
    private Object msgCount;

    private int mCurTab;
    private int mIndex = 0;
    private static final int FIRSTTAB = 0;
    private static final int SECONDTAB = 1;
    private static final int THIRDTAB = 2;
    private static final int FOURTAB = 3;
    private static final int FIVETAB = 4;
    private int []total = {FIRSTTAB,SECONDTAB,THIRDTAB,FOURTAB,FIVETAB};

    private PercentFragment mPercentFragment;
    private ShowNowFragment mShowNowFragment;
    private PushFragment mPushFragment;
    private WhatNowFragment mWhatNowFragment;
    private WhereNowFragment mWhereNowFragment;
    private JumpLoginFragment mJumpLoginFragment;

    private TextView [] mTextViews = new TextView[5];
    private Integer [] mIconNormals = new Integer[5];
    private Integer [] mIconSelects = new Integer[5];
    private static Fragment[] fragments = new Fragment[5];
    private FrameLayout mFrameLayout;
    private View TitleView;
    private String mTitles= null;

    private View mFooterView;
    private TextView mTvPlayWhat,mTvPlayWhere,mTvPush,mTvPlayShow,mTvPersent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //当发现新版本后提示更新
//        if (!SharedPreferencesUtil.getBooleanValue(mContext, DataConstants.REMIND_UPDATE_VERSON)){
//            showUpdataDialDialog(UPDATE_APP_VERSON_URL);
//        }
        SharedPreferencesUtil.setValue(mContext, KeysConstans.ISOPEN, "1");
//        EventBus.getDefault().register(this);
        initView();
        setCurTab(FIRSTTAB);//默认展示哪一个fragment
        getmsgCount();//接受消息通知

    }

    private void initView() {
        getTitleView().setVisibility(View.GONE);
        mFooterView = findViewById(R.id.foot_view_mainAc);
        mTvPlayWhat = (TextView) mFooterView.findViewById(R.id.tv_foottab_what);
        mTvPlayWhere = (TextView) mFooterView.findViewById(R.id.tv_foottab_where);
        mTvPush = (TextView) mFooterView.findViewById(R.id.tv_foottab_push);
        mTvPlayShow = (TextView) mFooterView.findViewById(R.id.tv_foottab_show);
        mTvPersent = (TextView) mFooterView.findViewById(R.id.tv_foottab_me);

        mTextViews[0] = mTvPlayWhat;
        mTextViews[1] = mTvPlayWhere;
        mTextViews[2] = mTvPlayShow;
        mTextViews[3] = mTvPersent;
        mTextViews[4] = mTvPush;
//        mTvContents[0] = mTvNewsContent;
//        mTvContents[1]=mTvDiscoveryContent;
//        mTvContents[2]=mTvCourseContent;
//        mTvContents[3] = mTvMyselfContent;
        mIconNormals[0] = R.drawable.zw_what_unselected;
        mIconNormals[1] = R.drawable.zw_where_unselected;
        mIconNormals[2] = R.drawable.zw_show_unselected;
        mIconNormals[3] = R.drawable.zw_me_unselected;
        mIconNormals[4] = R.drawable.zw_release_selected;

        mIconSelects[0] = R.drawable.zw_what_selected;
        mIconSelects[1] = R.drawable.zw_where_selected;
        mIconSelects[2] = R.drawable.zw_show_selected;
        mIconSelects[3] = R.drawable.zw_me_selected;
        mIconSelects[4] = R.drawable.zw_release_selected;


        mTvPlayWhat.setOnClickListener(this);
        mTvPlayWhere.setOnClickListener(this);
        mTvPush.setOnClickListener(this);
        mTvPlayShow.setOnClickListener(this);
        mTvPersent.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.tv_foottab_what:
                StatisticsUtil.onEvent(mContext, StatisticConstants.EVENT_MAIN_TAB,"玩啥");
                setCurTab(FIRSTTAB);
                break;
            case R.id.tv_foottab_where:
                StatisticsUtil.onEvent(mContext, StatisticConstants.EVENT_MAIN_TAB,"去哪");
                setCurTab(SECONDTAB);
                break;
            case R.id.tv_foottab_push:
                StatisticsUtil.onEvent(mContext, StatisticConstants.EVENT_MAIN_TAB,"发布");
                setCurTab(FIVETAB);
                break;
            case R.id.tv_foottab_show:
                StatisticsUtil.onEvent(mContext, StatisticConstants.EVENT_MAIN_TAB,"晒玩");
                setCurTab(THIRDTAB);
                break;
            case R.id.tv_foottab_me:
                StatisticsUtil.onEvent(mContext, StatisticConstants.EVENT_MAIN_TAB,"我的");
                setCurTab(FOURTAB);
                break;
        }
    }

    @Override
    public int getBodyView() {
        return R.layout.activity_main;
    }

    @Override
    public Object getTitleString() {
        return mTitles;
    }

    //展示哪一个fragment
    private void setCurTab(int curTab) {
        this.mCurTab = curTab;
        hidAllFragment(mCurTab);
        switch (mCurTab){
            case FIRSTTAB:
                if (mWhatNowFragment == null) {
                    mWhatNowFragment = new WhatNowFragment();
                    fragments[0] = mWhatNowFragment;

                }
                if (!mWhatNowFragment.isAdded()) {
                    add(R.id.tab_content, mWhatNowFragment);
                    mTitles = "玩儿";
                }
                break;
            case SECONDTAB:
                if (mWhereNowFragment == null) {
                    mWhereNowFragment = new WhereNowFragment();
                    fragments[1] = mWhereNowFragment;
                }
                if (!mWhereNowFragment.isAdded()) {
                    add(R.id.tab_content, mWhereNowFragment);
                    mTitles = "去哪玩";
                }
                break;
            case FIVETAB://发布页面
                if (mPushFragment == null) {
                    mPushFragment = new PushFragment();
                    fragments[4] = mPushFragment;
                }
                if (!mPushFragment.isAdded()) {
                    add(R.id.tab_content, mPushFragment);
                    mTitles = "发布";
                }
                break;
            case THIRDTAB:
                if (mShowNowFragment == null) {
                    mShowNowFragment = new ShowNowFragment();
                    fragments[2] = mShowNowFragment;
                }
                if (!mShowNowFragment.isAdded()) {
                    add(R.id.tab_content, mShowNowFragment);
                    mTitles = "晒玩";
                }
                break;
            case FOURTAB:
                if (TextUtils.isEmpty(SharedPreferencesUtil.getStringValue(mContext,DataConstants.USERID))) {//当正式运行时改为’非‘
                    if (mPercentFragment == null) {
                        mPercentFragment = new PercentFragment();
                        fragments[3] = mPercentFragment;
                    }
                    if (!mPercentFragment.isAdded()) {
                        add(R.id.tab_content, mPercentFragment);
                        mTitles = "我玩";
                    }
                }else{
                    if (mJumpLoginFragment == null) {
                        mJumpLoginFragment = new JumpLoginFragment();
                        fragments[3] = mJumpLoginFragment;
                    }
                    if (!mJumpLoginFragment.isAdded()) {
                        add(R.id.tab_content, mJumpLoginFragment);
                    }
                }
                break;
            default:
                break;
        }
    }

    private void hidAllFragment(int mCurTab) {
        try {
            for (int i = 0; i < total.length; i++) {
                if (mCurTab == total[i]) {
                    show(fragments[i]);
                    Drawable drawable = mContext.getResources().getDrawable(mIconSelects[i]);
                    drawable.setBounds(0,0,drawable.getMinimumWidth(), drawable.getMinimumHeight());//必须设置图片大小，否则不显示
                    mTextViews[i].setCompoundDrawables(null, drawable, null, null);
                    mTextViews[i].setTextColor(getResources().getColor(R.color.logincolor));
                } else {
                    hide(fragments[i]);
                    Drawable drawable1 = mContext.getResources().getDrawable(mIconNormals[i]);
                    drawable1.setBounds(0,0,drawable1.getMinimumWidth(), drawable1.getMinimumHeight());//必须设置图片大小，否则不显示
                    mTextViews[i].setCompoundDrawables(null, drawable1, null, null);
                    mTextViews[i].setTextColor(getResources().getColor(R.color.hintcolor));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void getmsgCount() {
        //当mUserId不为空时，联网获取数据，判断是否有未读消息
//        if (!TextUtils.isEmpty(SharedPreferencesUtil.getStringValue(mContext,DataConstants.USERID))){
//            new Timer().schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    checkUnReadmsgCount(UNREAD_MSG_URL);
//                }
//            },1500);
//        }
    }

    private void checkUnReadmsgCount(String url) {
        Map<String,String > params = new HashMap<>();
        params.put(DataConstants.USERID,SharedPreferencesUtil.getStringValue(mContext,DataConstants.USERID));
        VolleyManager.getInstance().postString(url, params, new RequestListener() {
            @Override
            public void requestSuccess(Object result) {
                //TODO 当联网成功后执行操作，显示未读信息到我的新消息栏
            }

            @Override
            public void requestError(VolleyError e) {

            }
        },UnreadMsgBean.class);
    }

    private void showUpdataDialDialog(String url){
        VolleyManager.getInstance().postString(url, new HashMap(), new RequestListener() {
            @Override
            public void requestSuccess(Object result) {
                UpdataInfoBean updataInfoBean = (UpdataInfoBean) result;
                UpdataInfoBean.Data data = updataInfoBean.getData();
                int oldVerson = Integer.parseInt(BallUtil.getAppVersionCode(mContext));//从手机内存中去出现有版本号
                int verSon = Integer.parseInt(data.getServerVersion());
                if (oldVerson<verSon){
                    normalUpdata(data.getUpgradeinfo(),data.getServerVersion(),data.getUpdateurl(),data.getLastForce());
                }
            }

            @Override
            public void requestError(VolleyError e) {

            }
        },UpdataInfoBean.class);
    }

    private View mDialogView;
    private TextView mTvVerson,mTvVersonDesc;
    private CheckBox mCbNoremind;
    private Button mBtnLeft,mBtnRight;
    private boolean isNoRemind = false;
    //版本更新提示框
    private void initDialog() {
        mDialogView = LayoutInflater.from(mContext).inflate(R.layout.update_verson_dialog,null);
        onCreateCustomDialog(mDialogView);
        mTvVerson = (TextView) mDialogView.findViewById(R.id.tv_update_verson);
        mTvVersonDesc = (TextView) mDialogView.findViewById(R.id.tv_update_verson_desc);
        mCbNoremind = (CheckBox) mDialogView.findViewById(R.id.cb_update_nolonger_remind);
        mBtnLeft = (Button) mDialogView.findViewById(R.id.btn_left);
        mBtnRight = (Button) mDialogView.findViewById(R.id.btn_right);
    }
    private void normalUpdata(final String message,final String verson,final String url,String foucs){
        initDialog();
        mTvVerson.setText("版本号：" + verson);
        mTvVersonDesc.setText("版本介绍：" + message);

        mBtnRight.setOnClickListener(new View.OnClickListener() {//更新
            @Override
            public void onClick(View v) {
                //TODO 开启后台服务进行更新下载
                SharedPreferencesUtil.setValue(mContext, DataConstants.REMIND_UPDATE_VERSON, isNoRemind);
                Intent mIntent = new Intent(mContext, UpdataService.class);
                mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mIntent.putExtra("url", url);
                mIntent.putExtra("message", message);
                mContext.startService(mIntent);
                mCustomDialog.dismiss();
            }
        });
        mCbNoremind.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isNoRemind = isChecked;
            }
        });
        if("1".equals(foucs)) {
            mBtnLeft.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SharedPreferencesUtil.setValue(mContext,DataConstants.REMIND_UPDATE_VERSON,isNoRemind);
                    mCustomDialog.dismiss();
                }
            });
        }else{
            mBtnLeft.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
           /* switch (requestCode){
                 case :

                break;
                default:
                    break;
            }*/
        }
    }
}
